package com.probox.common.entity.service.customer.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.probox.common.core.constant.CachePrefix;
import com.probox.common.core.enums.CategoryDepth;
import com.probox.common.core.enums.DataStatus;
import com.probox.common.core.exception.BaseException;
import com.probox.common.core.exception.ProductException;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.core.utils.StringUtils;
import com.probox.common.entity.domain.customer.CustomerLabel;
import com.probox.common.entity.domain.product.vo.OptionsSelect;
import com.probox.common.entity.mapper.customer.CustomerLabelMapper;
import com.probox.common.entity.service.customer.ICustomerLabelService;
import com.probox.common.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Transactional
public class CustomerLabelServiceImpl extends ServiceImpl<CustomerLabelMapper, CustomerLabel> implements ICustomerLabelService {

    @Autowired
    private CustomerLabelMapper customerLabelMapper;

    @Autowired
    private RedisService redisService;

    @Override
    public CustomerLabel selectCustomerLabelById(Long labelId) {
        return this.getById(labelId);
    }

    /**
     * 查询客户标签列表
     *
     * @param customerLabel 客户标签
     * @return 客户标签
     */
    @Override
    public List<CustomerLabel> queryList(CustomerLabel customerLabel) {

        QueryWrapper<CustomerLabel> queryWrapper = Wrappers.query();
        if (StringUtils.isNotEmpty(String.valueOf(customerLabel.getLabelName())) && customerLabel.getLabelName() != null) {
            queryWrapper.like("label_name", customerLabel.getLabelName());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerLabel.getDataStatus())) && customerLabel.getDataStatus() != null) {
            queryWrapper.eq("DATA_STATUS", customerLabel.getDataStatus());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerLabel.getCategoryDepth())) && customerLabel.getCategoryDepth() != null) {
            queryWrapper.eq("CATEGORY_DEPTH", customerLabel.getCategoryDepth());
        }

        queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
        if (StringUtils.isNotEmpty(String.valueOf(customerLabel.getDataPriority())) && customerLabel.getDataPriority() != null) {
            queryWrapper.orderByAsc("DATA_PRIORITY");
        } else {
            queryWrapper.orderByAsc("DATA_PRIORITY");
            queryWrapper.orderByDesc("UPDATE_TIME");
        }

        return customerLabelMapper.selectList(queryWrapper);
    }

    @Override
    public Integer selectCategoryCount(CustomerLabel customerLabel) {
        QueryWrapper<CustomerLabel> queryWrapper = Wrappers.query();
        if (StringUtils.isNotEmpty(String.valueOf(customerLabel.getLabelName())) && customerLabel.getLabelName() != null) {
            queryWrapper.like("label_name", customerLabel.getLabelName());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerLabel.getDataStatus())) && customerLabel.getDataStatus() != null) {
            queryWrapper.eq("DATA_STATUS", customerLabel.getDataStatus());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerLabel.getCategoryDepth())) && customerLabel.getCategoryDepth() != null) {
            queryWrapper.eq("CATEGORY_DEPTH", customerLabel.getCategoryDepth());
        }

        queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
        if (StringUtils.isNotEmpty(String.valueOf(customerLabel.getDataPriority())) && customerLabel.getDataPriority() != null) {
            queryWrapper.orderByAsc("DATA_PRIORITY");
        } else {
            queryWrapper.orderByAsc("DATA_PRIORITY");
            queryWrapper.orderByDesc("UPDATE_TIME");
        }
        return customerLabelMapper.selectList(queryWrapper).size();
    }


    /**
     * 新增客户标签
     *
     * @param customerLabel 客户标签
     * @return 结果
     */
    @Override
    public boolean insertProductCategory(CustomerLabel customerLabel) {
        // 分类名称不为重名
        Integer result = queryCategoryName(customerLabel);
        if (result > 0) {
            throw new ProductException("客户标签名称不能重名！");
        }
        customerLabel.setUpdateUid(SecurityUtils.getUserId());
        customerLabel.setUpdateName(SecurityUtils.getUsername());
        customerLabel.setUpdateTime(DateUtil.date());
        //customerLabel.setDataStatus(DataStatus.invalid.getKey());
        if (DataStatus.valid.getKey().equals(customerLabel.getDataStatus())) {
            if (CategoryDepth.two.getKey().equals(customerLabel.getCategoryDepth()))
                redisService.deleteObject(CachePrefix.PRODUCT_CATEGORY_TWO_BANNER + customerLabel.getLabelPid());
        }
        if (CategoryDepth.one.getKey().equals(customerLabel.getCategoryDepth())) {
            redisService.deleteObject(CachePrefix.PRODUCT_CATEGORY_TOP + SecurityUtils.getPlatformId());
        }
        // redisService.deleteObject(CachePrefix.PRODUCT_CATEGORY_CASCADER + SecurityUtils.getPlatformId());
        return this.save(customerLabel);
    }

    /**
     * 修改客户标签
     *
     * @param customerLabel 客户标签
     * @return 结果
     */
    @Override
    public boolean updateProductCategory(CustomerLabel customerLabel) {
        // 分类名称不为重名
        Integer result = queryCategoryName(customerLabel);
        if (result > 0) {
            throw new ProductException("客户标签名称不能重名！");
        }
//        if (DataStatus.invalid.getKey().equals(customerLabel.getDataStatus())) {
//            ProductInfo info = new ProductInfo();
//            if (CategoryDepth.one.getKey().equals(customerLabel.getCategoryDepth()))
//                info.setCategoryUidOne(customerLabel.getLabelId());
//            if (CategoryDepth.two.getKey().equals(customerLabel.getCategoryDepth()))
//                info.setCategoryUidTwo(customerLabel.getLabelId());
//            if (CategoryDepth.three.getKey().equals(customerLabel.getCategoryDepth()))
//                info.setCategoryUidThree(customerLabel.getLabelId());
////            if (iProductInfoService.useProduct(info)) throw new ProductException("该商品分类已被使用,无法无效！");
//        }
        customerLabel.setUpdateUid(SecurityUtils.getUserId());
        customerLabel.setUpdateName(SecurityUtils.getUsername());
        customerLabel.setUpdateTime(DateUtil.date());
        if (CategoryDepth.one.getKey().equals(customerLabel.getCategoryDepth())) {
            redisService.deleteObject(CachePrefix.PRODUCT_CATEGORY_TOP + SecurityUtils.getPlatformId());
        }
        if (CategoryDepth.two.getKey().equals(customerLabel.getCategoryDepth()))
            redisService.deleteObject(CachePrefix.PRODUCT_CATEGORY_TWO_BANNER + customerLabel.getLabelPid());
        return this.updateById(customerLabel);
    }

    /**
     * 批量删除客户标签
     *
     * @param categoryUids 需要删除的客户标签ID
     * @return 结果
     */
    @Override
    public boolean deleteProductCategoryByIds(Long[] categoryUids) {
        UpdateWrapper<CustomerLabel> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("label_id", Arrays.asList(categoryUids));
        updateWrapper.set("DATA_STATUS", DataStatus.delete.getKey());
        updateWrapper.set("UPDATE_UID", SecurityUtils.getUserId());
        updateWrapper.set("UPDATE_NAME", SecurityUtils.getUsername());
        updateWrapper.set("UPDATE_TIME", DateUtil.date());
        boolean update = this.update(updateWrapper);
        if (update) {
            UpdateWrapper<CustomerLabel> updateWrappers = new UpdateWrapper<>();
            updateWrappers.in("label_pid", Arrays.asList(categoryUids));
            updateWrappers.set("DATA_STATUS", DataStatus.delete.getKey());
            updateWrappers.set("UPDATE_UID", SecurityUtils.getUserId());
            updateWrappers.set("UPDATE_NAME", SecurityUtils.getUsername());
            updateWrappers.set("UPDATE_TIME", DateUtil.date());
            this.update(updateWrappers);
        }
        return update;
    }

    /**
     * 修改客户标签状态
     *
     * @param customerLabel 客户标签
     * @return 结果
     */
    @Override
    public boolean updateCategoryStatus(CustomerLabel customerLabel) {
        if (CategoryDepth.one.getKey().equals(customerLabel.getCategoryDepth())) {
            redisService.deleteObject(CachePrefix.PRODUCT_CATEGORY_TOP + SecurityUtils.getPlatformId());
        }
        if (CategoryDepth.two.getKey().equals(customerLabel.getCategoryDepth()))
            redisService.deleteObject(CachePrefix.PRODUCT_CATEGORY_TWO_BANNER + customerLabel.getLabelPid());
        CustomerLabel byId = this.getById(customerLabel.getLabelId());
        if (ObjectUtil.isEmpty(byId)) throw new BaseException("标签不存在");
        boolean b = this.updateProductCategory(customerLabel);
        if (byId.getLabelPid() == 0) {
            UpdateWrapper<CustomerLabel> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("label_pid", byId.getLabelId());
            updateWrapper.eq("DATA_STATUS", DataStatus.valid.getKey());
            updateWrapper.set("DATA_STATUS", DataStatus.invalid.getKey());
            updateWrapper.set("UPDATE_UID", SecurityUtils.getUserId());
            updateWrapper.set("UPDATE_NAME", SecurityUtils.getUsername());
            updateWrapper.set("UPDATE_TIME", DateUtil.date());
            return this.update(updateWrapper);
        }
        return b;
    }


    /**
     * 查询该等级的类别
     *
     * @param depth 等级
     * @return
     */
    @Override
    public List<CustomerLabel> getCategoryDepthList(String depth, Long uid) {
        QueryWrapper<CustomerLabel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("CATEGORY_DEPTH", depth);
        queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
        return customerLabelMapper.selectList(queryWrapper);
    }

    @Override
    public List<CustomerLabel> getCategoryOne(String depth, Long uid) {
        String key = CachePrefix.PRODUCT_CATEGORY_TOP + uid;
        List<CustomerLabel> cacheList = redisService.getCacheList(key);
        if (ObjectUtil.isEmpty(cacheList)) {
            QueryWrapper<CustomerLabel> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("CATEGORY_DEPTH", depth);
            queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
            queryWrapper.eq("IS_SHOW", "1");
            queryWrapper.orderByAsc("DATA_PRIORITY");
            cacheList = customerLabelMapper.selectList(queryWrapper);
            redisService.setCacheList(key, cacheList);
            redisService.expire(key, 1L, TimeUnit.DAYS);
        }
        return cacheList;

    }

    /**
     * 查询类别重名
     *
     * @param category
     * @return
     */
    @Override
    public Integer queryCategoryName(CustomerLabel category) {
        QueryWrapper<CustomerLabel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("label_name", category.getLabelName());
        //
        queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
        queryWrapper.eq("CATEGORY_DEPTH", category.getCategoryDepth());
        if (ObjectUtil.isNotEmpty(category.getLabelId())) {
            queryWrapper.ne("label_id", category.getLabelId());
        }
        return customerLabelMapper.selectCount(queryWrapper);
    }

    /**
     * 获取分类的级联
     *
     * @return
     */
    @Override
    public List<OptionsSelect> selectOptionList() {
        List<OptionsSelect> collect = null;
        CustomerLabel customerLabel = new CustomerLabel();
        customerLabel.setDataStatus(DataStatus.valid.getKey());
        customerLabel.setDataPriority(1L);
        List<CustomerLabel> list = this.queryList(customerLabel);
        List<CustomerLabel> returnList = new ArrayList<CustomerLabel>();
        List<Long> tempList = new ArrayList<Long>();
        for (CustomerLabel category : list) {
            tempList.add(category.getLabelId());
        }
        for (Iterator<CustomerLabel> iterator = list.iterator(); iterator.hasNext(); ) {
            CustomerLabel category = (CustomerLabel) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(category.getLabelPid())) {
                recursionFn(list, category);
                returnList.add(category);
            }
        }
        if (returnList.isEmpty()) {
            returnList = list;
        }
        collect = returnList.stream().map(OptionsSelect::new).collect(Collectors.toList());
        return collect;
    }


    /**
     * 递归列表
     *
     * @param list
     * @param t
     */
    private void recursionFn(List<CustomerLabel> list, CustomerLabel t) {
        // 得到子节点列表
        List<CustomerLabel> childList = getChildList(list, t);
        t.setChildren(childList);
        for (CustomerLabel tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<CustomerLabel> getChildList(List<CustomerLabel> list, CustomerLabel t) {
        List<CustomerLabel> tlist = new ArrayList<CustomerLabel>();
        Iterator<CustomerLabel> it = list.iterator();
        while (it.hasNext()) {
            CustomerLabel n = (CustomerLabel) it.next();
            if (n.getLabelPid().longValue() == t.getLabelId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    private boolean hasChild(List<CustomerLabel> list, CustomerLabel t) {
        return getChildList(list, t).size() > 0 ? true : false;
    }

}
